from typing import List
from .model import ResourceNews

from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
    get,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()

# 设置过滤字段
class Filters(FuFilters):
        
    des: str = Field(None, alias='des')    
    code: int = Field(None, alias='code')    
    name: str = Field(None, alias='name')


# 设置请求接收字段
class ResourceNewsSchemaIn(ModelSchema):

    class Config:
        model = ResourceNews
        model_exclude = ['create_time', 'update_time', 'id']


# 设置响应字段
class ResourceNewsSchemaOut(ModelSchema):

    class Config:
        model = ResourceNews
        model_fields = '__all__'


# 创建ResourceNews
@router.post('/resource_news', response=ResourceNewsSchemaOut)
def create_resource_news(request, data: ResourceNewsSchemaIn):
    resource_news = create(request, data, ResourceNews)
    return resource_news


# 删除ResourceNews
@router.delete('/resource_news/{id}')
def delete_resource_news(request, id: str):
    delete(id, ResourceNews)
    return {'success': True}

# 更新ResourceNews
@router.put('/resource_news/{id}', response=ResourceNewsSchemaOut)
def update_resource_news(request, id: str, data: ResourceNewsSchemaIn):
    resource_news = update(request, id, data, ResourceNews)
    return resource_news

@router.get("/resource_news/{id}", response=ResourceNewsSchemaOut)
def get_resource_news(request, id: str):
    resource_news = get(request, id, ResourceNews)
    return resource_news

# 获取ResourceNews
@router.get('/resource_news', response=List[ResourceNewsSchemaOut])
@paginate(MyPagination)
def list_resource_news(request, filters: Filters = Query(...)):
    qs = retrieve(request, ResourceNews, filters)
    return qs


# 导入
@router.get('/resource_news/all/export')
def export_resource_news(request):
    export_fields = ('des', 'code', 'name', )
    return export_data(request, ResourceNews, ResourceNewsSchemaOut, export_fields)


# 导出
@router.post('/resource_news/all/import')
def import_resource_news(request, data: ImportSchema):
    import_fields = ('des', 'code', 'name', )
    return import_data(request, ResourceNews, ResourceNewsSchemaIn, data, import_fields)
    